package com.sedireco.test;

import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.graphics.ImageFormat;
import android.graphics.Matrix;
import android.graphics.SurfaceTexture;
import android.hardware.Camera;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;

public class MainActivity extends AppCompatActivity implements Camera.PreviewCallback, TextureView.SurfaceTextureListener {

    private TextureView textureView;

    private Camera camera;
    private Matrix mirrorMatrix;
    private int cameraId;

    private static final String[] PERMISSIONS = new String[]{
            Manifest.permission.CAMERA
    };
    private static final int MY_PERMISSION_REQUEST_CODE = 1001;

    private static final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initialViews();
        //申请权限
        checkPermissionAllGranted();
    }

    private void initialViews() {
        textureView = (TextureView) findViewById(R.id.textureView);
    }

    private void checkPermissionAllGranted() {
        for (String permission : PERMISSIONS) {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                //提示动态授权
                ActivityCompat.requestPermissions(this, PERMISSIONS, MY_PERMISSION_REQUEST_CODE);
                return;
            }
        }
        //打开相机
        openCamera();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == MY_PERMISSION_REQUEST_CODE) {
            boolean isAllGranted = true;
            //判断是否所有的权限都已经授予了
            for (int grant : grantResults) {
                if (grant != PackageManager.PERMISSION_GRANTED) {
                    isAllGranted = false;
                    break;
                }
            }
            if (isAllGranted) {
                //打开相机
                openCamera();
            } else {
                //重新授权
                checkPermissionAllGranted();
            }
        }
    }

    private void openCamera() {
        Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
        int number = Camera.getNumberOfCameras();
        for (int camIdx = 0; camIdx < number; ++camIdx) {
            Camera.getCameraInfo(camIdx, cameraInfo);
            if (cameraInfo.facing == 0 && camIdx == 1) {
                //获取cameraId
                cameraId = camIdx;
                //打开相机
                camera = Camera.open(cameraId);
                //设置相机参数
                Camera.Parameters parameters = camera.getParameters();
                parameters.setPreviewFormat(ImageFormat.NV21);
                parameters.setPictureFormat(ImageFormat.JPEG);
                parameters.setPreviewSize(1280, 720);
                camera.setParameters(parameters);
                //相机打开成功
                textureView.setSurfaceTextureListener(this);
                textureView.setVisibility(View.VISIBLE);
                //yuv帧水平翻转
                mirrorMatrix = new Matrix();
                mirrorMatrix.setScale(-1, 1, textureView.getWidth() / 2.0f, 0);
                return;
            }
        }
    }

    @Override
    public void onPreviewFrame(byte[] data, Camera camera) {
        //获取相机预览回调数据data
    }

    @Override
    public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
        try {
            //开启预览
            camera.setPreviewTexture(surface);
            camera.setDisplayOrientation(getCameraAngle(this));
            camera.startPreview();
            camera.setPreviewCallback(this);
            textureView.setTransform(mirrorMatrix);
        } catch (Exception e) {
            Log.e(TAG, "onSurfaceTextureAvailable error: " + e);
        }
    }

    @Override
    public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
    }

    @Override
    public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
        //关闭预览
        if (camera != null) {
            camera.setPreviewCallback(null);
            camera.stopPreview();
        }
        return false;
    }

    @Override
    public void onSurfaceTextureUpdated(SurfaceTexture surface) {

    }

    private int getCameraAngle(Activity activity) {
        Camera.CameraInfo info = new Camera.CameraInfo();
        Camera.getCameraInfo(cameraId, info);
        int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();
        int degrees = 0;
        switch (rotation) {
            case Surface.ROTATION_0:
                degrees = 0;
                break;
            case Surface.ROTATION_90:
                degrees = 90;
                break;
            case Surface.ROTATION_180:
                degrees = 180;
                break;
            case Surface.ROTATION_270:
                degrees = 270;
                break;
            default:
                break;
        }
        int rotateAngle;
        if (info.facing == 1) {
            rotateAngle = (info.orientation + degrees) % 360;
            rotateAngle = (360 - rotateAngle) % 360;
        } else {
            rotateAngle = (info.orientation - degrees + 360) % 360;
        }
        return rotateAngle;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (camera != null) {
            //关闭相机
            camera.stopPreview();
            camera.setPreviewCallback(null);
            camera.release();
            camera = null;
        }
    }

}
